/**
 * 
 */

//
import React, { useEffect, useRef, useState, useCallback } from "react";
import { message } from "antd";
// import {FCForm} from "@components";
import Search from "./components/Search";
import styles from './style/realTimeRisk.module.css'
import { findAreaSubjectSum } from "../../../apis/realTimeRiskApi";

const RealTimeRisk = () => {

  const [spinning, setSpinning] = useState(false);
  const [addressList, setAddressList] = useState([]); // 地址列表

  let lastAreaName = []; //最后的AreaName
  let currentBdaryList = []; //存放当前行政区覆盖物数组
  let currentaddress = ""; //当前地址
  let isSearchSubmit = false; //是否点击了查询
  let banZoomend = false; //禁止缩放地图

  let map = null;
  const geoc = new BMapGL.Geocoder(); //用于获取用户的地址解析
  function initMap() {
    map = new BMapGL.Map(styles.container); //创建地图Map实例
    map.centerAndZoom(new BMapGL.Point(105.32257303547965, 34.013674492029665), 6); //初始化地图，设置中心坐标点和地图级别
    map.enableScrollWheelZoom(true); //启动地图滚轮放大/缩小
    map.disableDoubleClickZoom(); //取消地图双击缩放
    map.setMinZoom(5); //地图最小缩放值
    map.addEventListener("dragend", dragendFunc);
    map.addEventListener("zoomend", zoomendFunc);

    React.Map = map;
  }

  useEffect(() => {
    initMap();
    setLastAreaName();
  }, [map]);

  //地图结束缩放
  function zoomendFunc(e) {
    //点击查询的时候直接返回
    if (isSearchSubmit || banZoomend) return;
    console.log("缩放结束");
    setLastAreaName();
  }

  //地图结束拖拽
  function dragendFunc(e) {
    console.log("拖拽结束");
    const zoom = map.getZoom();
    if (zoom >= 8) {
      setLastAreaName()
    }
  }

  // 设置全局lastAreaName
  function setLastAreaName() {
    const zoom = map.getZoom();
    const point = map.getCenter();
    geoc.getLocation(point, function (rs) {
      const addComp = rs.addressComponents;
      const province = addComp.province; //获取省份
      const city = addComp.city; //获取城市
      const district = addComp.district; //获取区域
      if (zoom < 8) {
        lastAreaName = "中国";
      } else if (zoom < 11) {
        lastAreaName = province;
      } else if (zoom < 13) {
        lastAreaName = province + city;
      }
      // console.log('setLastAreaName==>',lastAreaName);
      setLabelOrMarker();
    })
  }

  //解析地址信息，分别设置省市区标记
  function setLabelOrMarker() {
    const center = map.getCenter();
    const zoom = map.getZoom();
    // console.log(center);
    geoc.getLocation(center, function (rs) {
      // banZoomend = false //取消禁用缩放时间
      // console.log(rs);

      const addComp = rs.addressComponents;
      const province = addComp.province; //获取省份
      const city = addComp.city; //获取城市
      const district = addComp.district; //区
      const street = addComp.street; //街
      const streetNumber = addComp.streetNumber;

      // const location_name = province + city + district + street + streetNumber;
      // console.log(location_name, zoom);
      let address = "中国";
      if (zoom < 8) {
        // console.log(currentaddress, address);
        // console.log('zoom < 8',currentaddress === address);
        if (currentaddress === address) return; // 相同区域直接返回，不再发起请求
        getFindAreaSubjectSum({}, address);
        return;
      }
      if (zoom < 11) {
        address = province;
        if (currentaddress === address) return; // 相同区域直接返回，不再发起请求
        getFindAreaSubjectSum({ areaName: province }, address);
        return;
      }
      if (zoom < 13) {
        address = province + city;
        if (currentaddress === address) return; // 相同区域直接返回，不再发起请求
        getFindAreaSubjectSum({ areaName: city }, address);
        return;
      }
      if (zoom >= 13) {
        const params = {
          provinceName: province,
          cityName: city,
          countyName: district,
          provinceCode: "",
          cityCode: "",
          countyCode: "",
          untiCode: "",
          riskCode: "",
          insured: "",
          policyNo: "",
        };
        address = province + city + district;
        // console.log(`${currentaddress}<===>${address}`);
        if (currentaddress === address) return; // 相同区域直接返回，不再发起请求
        // getMarkerPolicyDetails(params, address);
        // return;
      }
    });
  }

  function disposeSpinning(data, error) {
    if (error) {
      setSpinning(false);
      return true
    }

    if (!data.length) {
      setSpinning(false);
      message.info('地图中心区域未查询到相关数据');
      return true
    }

    return false
  }

  //获取省市区汇总数据
  async function getFindAreaSubjectSum(params, address) {
    map.clearOverlays();
    currentaddress = address;
    setSpinning(true);

    const { data, error } = await findAreaSubjectSum(params)

    const isReturn = disposeSpinning(data, error)
    if (isReturn) {
      return
    }
    setAddressList(data)

    currentBdaryList = [];
    data.forEach((item) => {
      addMapLabel(item, data.length);
    });
  }

  //根据经纬度添加文本标记
  function addMapLabel(data, dataLength) {
    const { areaName, count, longitude, latitude } = data;

    //经纬度为空，直接返回
    if (!longitude || !latitude) return;

    const point = new BMapGL.Point(longitude, latitude);
    const opts = {
      position: point, //指定文本标注所在地理位置
      offset: new BMapGL.Size(-42, -42), //设置文本偏移量
    };
    const content = `
      <div class="text-box">
        <div class="text-box-title">${areaName}</div>
        <div class="text-box-count">${count}</div>
      </div>
    `;

    // 创建文本标注对象
    const label = new BMapGL.Label(content, opts);
    label.setStyle({
      borderRradius: "50%",
      overflow: "hidden",
      backgroundColor: "transparent",
      borderColor: "transparent",
    });

    map.addOverlay(label);

    currentBdaryList.push(areaName);

    const zoom = map.getZoom();
    if (zoom > 11) {
      let div = document.createElement("div");
      div.innerHTML = `
      <div class="content-box">
        <div>区域名称：区域名称</div>
        <div>归属机构：归属机构</div>
        <div>天气类型：天气类型</div>
        <div>风险等级：风险等级</div>
        <div>产品类型：产品类型</div>
        <div>受灾标数量:1000</div>
        <div>总保额:￥333W</div>
        <div>总保费:￥3W</div>
        <div>总理赔:￥333W</div>
      </div>
      `
      var steelOpts = {
        offset: new BMapGL.Size(10, -35) // 右上偏移
      }
      //创建信息窗口
      let infoWindow = new BMapGL.InfoWindow(div, steelOpts)
      //文本标注对象事件监听
      label.addEventListener("click", function () {
        map.openInfoWindow(infoWindow, point)
        // console.log("点击了");
      });
    }

    if (dataLength === currentBdaryList.length) {
      setSpinning(false);
    }

    // 添加行政区域覆盖物
    // const BoundaryName = map.getZoom() < 8 ? areaName : lastAreaName + areaName;
    setTimeout(() => {
      const textBox = label.ca?.firstElementChild;

      textBox.onclick = function (e) {
        const ev = e || window.event;
        setMapZoom(point)
      }
    }, 100);
  }

  // 点击文本标记放大地图
  function setMapZoom(point) {
    const zoom = map.getZoom();
    if (zoom < 8) {
      map.centerAndZoom(point, 9);
      return;
    }
    if (zoom < 11) {
      map.centerAndZoom(point, 12);
      return;
    }
    if (zoom < 13) {
      map.centerAndZoom(point, 14);
      return;
    }
  }

  function searchSubmit(params) {
    // hideDetailsPanel()
    const formData = {
      provinceCode: params.province?.value,
      cityCode: params.city?.value,
      countyCode: params.county?.value,
      untiCode: params.unti?.value,
      riskCode: params.risk?.value,
      insured: params.insured,
      policyNo: params.policyNo,
    }
    // console.log(formData);
    // map.clearOverlays();
    isSearchSubmit = true
    const { provinceCode, cityCode, countyCode, untiCode, riskCode, insured, policyNo } = formData
    const provinceText = params.province?.label || ''
    const cityText = params.city?.label || ''
    const countyText = params.county?.label || ''

    if (countyCode || untiCode || riskCode || insured || policyNo) {
      getMarkerPolicyDetails(formData)
      return
    }

    const areaCode = cityCode || provinceCode
    const areaName = provinceText + cityText + countyText
    const zoom = countyCode ? 14 : cityCode ? 12 : provinceCode ? 9 : 0

    lastAreaName = cityCode ? provinceText : provinceCode ? '中国' : '中国'
    // console.log(lastAreaName);
    // console.log(zoom);
    // console.log(areaName);
    // console.log(areaCode);

    geoc.getPoint(areaName, (point) => {
      map.centerAndZoom(point, zoom)
      getFindAreaSubjectSum({ areaCode });
    },
      lastAreaName
    );
  }

  const submit = useCallback((formData) => {
    searchSubmit(formData)
  }, [map])

  return (
    <div className={`page-content ${styles.realTimeRisk}`}>
      <Search submit={submit} />
      <div id={styles.container}></div>
    </div>
  );
};

export default RealTimeRisk;
